import { useEffect, useRef } from "react";
import styles from "./index.module.scss";
import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/Addons.js";

const DigitalHumanM = () => {
  const canvas = useRef<HTMLCanvasElement>(null);
  useEffect(() => {
    if (!canvas.current) return;

    // WebGL渲染器
    const renderer = new THREE.WebGLRenderer({
      antialias: true,
      canvas: canvas.current,
    });
    
    renderer.setSize(
      canvas.current.clientWidth,
      canvas.current.clientHeight,
      false
    );

    // 透视摄像机
    const fov = 50;
    const aspect = canvas.current.clientWidth / canvas.current.clientHeight;
    const near = 0.1;
    const far = 1000;
    const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
    camera.position.set(0, 1, 3);

    // 创建场景
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0xf0f0f0);

    // 添加环境光
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
    scene.add(ambientLight);

    // 添加方向光
    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
    directionalLight.position.set(5, 10, 5);
    scene.add(directionalLight);

    // 添加点光源
    const pointLight = new THREE.PointLight(0xffffff, 0.5);
    pointLight.position.set(-5, 5, 5);
    scene.add(pointLight);

    let model: THREE.Group | null = null;

    // 加载 GLTF 模型
    const gltfLoader = new GLTFLoader();
    const url = "/glb/szl.glb"; // Vite 中 public 文件夹的文件路径不需要 /public 前缀

    gltfLoader.load(
      url,
      (gltf) => {
        model = gltf.scene;
        scene.add(model);

        // 计算模型边界框并调整相机位置
        const box = new THREE.Box3().setFromObject(model);
        const center = box.getCenter(new THREE.Vector3());
        const size = box.getSize(new THREE.Vector3());

        // 计算合适的相机距离
        const maxDim = Math.max(size.x, size.y, size.z);
        const fov = camera.fov * (Math.PI / 180);
        let cameraZ = Math.abs(maxDim / 2 / Math.tan(fov / 2));
        cameraZ *= 1.5; // 增加一些距离以便更好地查看

        // 调整相机位置
        camera.position.set(center.x, center.y, center.z + cameraZ);
        camera.lookAt(center);

        // 调整渲染器大小
        const handleResize = () => {
          if (!canvas.current) return;
          const width = canvas.current.clientWidth;
          const height = canvas.current.clientHeight;
          camera.aspect = width / height;
          camera.updateProjectionMatrix();
          renderer.setSize(width, height, false);
        };

        window.addEventListener("resize", handleResize);

        // 初始渲染
        renderer.render(scene, camera);
      },
      (progress) => {
        // 加载进度
        console.log(
          "加载进度:",
          (progress.loaded / progress.total) * 100 + "%"
        );
      },
      (error) => {
        // 加载错误
        console.error("模型加载失败:", error);
      }
    );

    // 渲染循环
    function render(time: number) {
      time *= 0.001; // 将时间单位变为秒

      // 如果模型已加载，可以添加旋转动画
      if (model) {
        model.rotation.y = time * 0.3; // 缓慢旋转
      }

      camera.aspect =
        canvas.current!.clientWidth / canvas.current!.clientHeight;
      camera.updateProjectionMatrix();
      renderer.render(scene, camera);

      requestAnimationFrame(render);
    }

    requestAnimationFrame(render);

    // 清理函数
    return () => {
      if (model) {
        scene.remove(model);
        model.traverse((child) => {
          if (child instanceof THREE.Mesh) {
            child.geometry.dispose();
            if (Array.isArray(child.material)) {
              child.material.forEach((mat) => mat.dispose());
            } else {
              child.material.dispose();
            }
          }
        });
      }
      renderer.dispose();
    };
  }, []);
  return (
    <div className={styles.container}>
      <canvas ref={canvas} style={{ height: "100%", width: "100%" }}></canvas>
    </div>
  );
};

export default DigitalHumanM;
